<?php

/**
 *	Class Appointments
 *  --------------
 *	Description : encapsulates methods and properties
 *	Written by  : ApPHP
 *  Updated	    : 12.02.2012
 *  Usage       : Core Class (ALL)
 *
 *	PUBLIC:				  	STATIC:				 		PRIVATE:
 * 	------------------	  	---------------     		---------------
 *	__construct             GetStaticMessage
 *	__destruct              VerifyAppointment
 *  BeforeUpdateRecord      DrawVerifyAppointment
 *  BeforeDeleteRecord      DrawAppointmentDetails
 *	BeforeDelete            DrawAppointmentSignIn
 *	                        DoAppointment
 *	                        
 *	                        
 *  1.0.0
 *      - 
 *      - 
 *      -
 *      -
 *      -
 *      
 **/


class Appointments extends MicroGrid {
	
	protected $debug = false;
	
	private static $static_message = '';
	private $status = '0';
	
	//==========================================================================
    // Class Constructor
	//==========================================================================
	function __construct()
	{		
		parent::__construct();
		
		global $objLogin;
		
		$this->params = array();
		
		## for standard fields
		if(isset($_POST['status']))   $this->params['status'] = prepare_input($_POST['status']);
		if(isset($_POST['additional_info']))   $this->params['additional_info'] = prepare_input($_POST['additional_info']);
		
		## for checkboxes 
		//$this->params['field4'] = isset($_POST['field4']) ? prepare_input($_POST['field4']) : '0';

		## for images (not necessary)
		//if(isset($_POST['icon'])){
		//	$this->params['icon'] = prepare_input($_POST['icon']);
		//}else if(isset($_FILES['icon']['name']) && $_FILES['icon']['name'] != ''){
		//	// nothing 			
		//}else if (self::GetParameter('action') == 'create'){
		//	$this->params['icon'] = '';
		//}

		## for files:
		// define nothing

		//$this->params['language_id'] = MicroGrid::GetParameter('language_id');
	
		//$this->uPrefix 		= 'prefix_';
		
		$access_by_usertype = (($objLogin->IsLoggedInAsPatient()) ? false: true);
		$change_appt_in_past = true;
		$rid = MicroGrid::GetParameter('rid');
		
		$this->primaryKey 	= 'id';
		$this->tableName 	= TABLE_APPOINTMENTS; 
		$this->dataSet 		= array();
		$this->error 		= '';
		$this->formActionURL = 'index.php?'.(($objLogin->IsLoggedInAsPatient()) ? 'patient=my_appointments' : 'admin=mod_appointments_management');		
		$this->actions      = array('add'=>false, 'edit'=>$access_by_usertype, 'details'=>true, 'delete'=>(($objLogin->IsLoggedInAs('owner', 'mainadmin') || ($objLogin->GetLoggedType() == 'patient'))  ? true : false));
		$this->actionIcons  = true;
		$this->allowRefresh = true;
		$this->allowTopButtons = false;
		$this->alertOnDelete = ''; // leave empty to use default alerts

		$this->allowLanguages = false;
		//$this->languageId  	= ($this->params['language_id'] != '') ? $this->params['language_id'] : Languages::GetDefaultLang();
		$this->WHERE_CLAUSE = (($objLogin->IsLoggedInAsPatient()) ? 'WHERE '.$this->tableName.'.patient_id = '.(int)$objLogin->GetLoggedID() : '');
		$this->ORDER_CLAUSE = 'ORDER BY '.$this->tableName.'.appointment_date DESC, '.$this->tableName.'.appointment_time DESC'; 
		
		$this->isAlterColorsAllowed = true;

		$this->isPagingAllowed = true;
		$this->pageSize = 30;

		$this->isSortingAllowed = true;

		$this->isExportingAllowed = $access_by_usertype;
		$this->arrExportingTypes = array('csv'=>true);
		
		// prepare doctors array		
		$total_doctors = Doctors::GetAllActive();
		$arr_doctors = array();
		foreach($total_doctors[0] as $key => $val){
			$arr_doctors[$val['id']] = $val['first_name'].' '.$val['middle_name'].' '.$val['last_name'];
		}
		// prepare array for whom
		$arr_for_whom = array('0'=>_FOR_ME, '1'=>_SOMEONE_ELSE);		
		// prepare statuses array		
		$arr_statuses_view = array('0'=>'<font color=#a3a300>'._RESERVED.'</font>',
								   '1'=>'<font color=#00a300>'._VERIFIED.'</font>',
							       '2'=>'<font color=#939393>'._CANCELED.'</font>');
		
		$arr_statuses_edit = array('0'=>'<font color=#a3a300>'._RESERVED.'</font>',
								   '1'=>'<font color=#00a300>'._VERIFIED.'</font>',
								   '2'=>'<font color=#939393>'._CANCELED.'</font>');
		
		// prepare trigger
		$sql = 'SELECT status, appointment_date FROM '.$this->tableName.' WHERE id = '.(int)$rid;
		$result = database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY, FETCH_ASSOC);
		if($result[1] > 0){
			if($result[0]['status'] == '1'){
				$arr_statuses_edit = array('1'=>'<font color=#00a300>'._VERIFIED.'</font>',
								           '2'=>'<font color=#939393>'._CANCELED.'</font>');
			}else if($result[0]['status'] == '2'){
				$arr_statuses_edit = array('2'=>'<font color=#939393>'._CANCELED.'</font>');				
			}
			if($result[0]['appointment_date'] < date('Y-m-d')){
				$change_appt_in_past = false;
			}
		}		
		
		///$this->isAggregateAllowed = false;
		///// define aggregate fields for View Mode
		///$this->arrAggregateFields = array(
		///	'field1' => array('function'=>'SUM'),
		///	'field2' => array('function'=>'AVG'),
		///);

		$date_format = get_date_format('view');
		$date_format_settings = get_date_format('view', true);
		///$date_format_edit = get_date_format('edit');
		///$datetime_format = get_datetime_format();
		$time_format = get_time_format(false);
		if($time_format == 'H:i'){
			$sql_time_format = '%H:%i';
		}else{
			$sql_time_format = '%l:%i %p';
		}
		///$currency_format = get_currency_format();
		$currency_symbol = Application::Get('currency_symbol');

		// define filtering fields
		$this->isFilteringAllowed = true;
		$this->arrFilteringFields = array(
			'#'      => array('table'=>TABLE_APPOINTMENTS, 'field'=>'appointment_number', 'type'=>'text', 'sign'=>'like%', 'width'=>'90px', 'visible'=>$access_by_usertype),
			_STATUS  => array('table'=>TABLE_APPOINTMENTS, 'field'=>'status', 'type'=>'dropdownlist', 'source'=>$arr_statuses_view, 'sign'=>'=', 'width'=>'', 'visible'=>$access_by_usertype),
			_DOCTOR  => array('table'=>TABLE_DOCTORS, 'field'=>'id', 'type'=>'dropdownlist', 'source'=>$arr_doctors, 'sign'=>'=', 'width'=>'160px', 'visible'=>true),
			_PATIENT => array('table'=>TABLE_PATIENTS, 'field'=>'last_name', 'type'=>'text', 'sign'=>'%like%', 'width'=>'110px', 'visible'=>$access_by_usertype),
			_DATE    => array('table'=>TABLE_APPOINTMENTS, 'field'=>'appointment_date', 'type'=>'calendar', 'date_format'=>$date_format_settings, 'sign'=>'=', 'width'=>'80px', 'visible'=>true),
		);

		//---------------------------------------------------------------------- 
		// VIEW MODE
		// format: strip_tags
		// format: nl2br
		// format: 'format'=>'date', 'format_parameter'=>'M d, Y, g:i A'
		// format: 'format'=>'currency', 'format_parameter'=>'european|2' or 'format_parameter'=>'american|4'
		//---------------------------------------------------------------------- 
		$this->VIEW_MODE_SQL = 'SELECT '.$this->tableName.'.'.$this->primaryKey.',
									'.$this->tableName.'.appointment_number,
									'.$this->tableName.'.appointment_description,
									'.$this->tableName.'.doctor_id,
									'.$this->tableName.'.patient_id,
									'.$this->tableName.'.appointment_date,
									DATE_FORMAT('.$this->tableName.'.appointment_time, "'.$sql_time_format.'") as appointment_time,
									'.$this->tableName.'.visit_duration,
									'.$this->tableName.'.visit_price,
									'.$this->tableName.'.additional_info,
									'.$this->tableName.'.status,
									'.$this->tableName.'.status_changed,
									'.$this->tableName.'.email_sent,
									CONCAT('.TABLE_DOCTORS.'.first_name, " ", '.TABLE_DOCTORS.'.middle_name, " ", '.TABLE_DOCTORS.'.last_name, " - <span class=gray>", '.TABLE_SPECIALITIES.'.name, "</span>") as doctor_name,
									CONCAT('.TABLE_PATIENTS.'.first_name, " ", '.TABLE_PATIENTS.'.last_name) as patient_name									
								FROM '.$this->tableName.'
									INNER JOIN '.TABLE_DOCTORS.' ON '.$this->tableName.'.doctor_id = '.TABLE_DOCTORS.'.id
									LEFT OUTER JOIN '.TABLE_PATIENTS.' ON '.$this->tableName.'.patient_id = '.TABLE_PATIENTS.'.id
									LEFT OUTER JOIN '.TABLE_SPECIALITIES.' ON '.$this->tableName.'.doctor_speciality_id = '.TABLE_SPECIALITIES.'.id
								';		
		// define view mode fields
		$this->arrViewModeFields = array(
			'appointment_number' => array('title'=>_APPOINTMENT_NUMBER, 'type'=>'label', 'align'=>'left', 'width'=>'120px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),
			'doctor_name'        => array('title'=>_DOCTOR, 'type'=>'label', 'align'=>'left', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),
			//'specialty_name'     => array('title'=>_SPECIALITY, 'type'=>'label', 'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),
			'patient_name'       => array('title'=>_PATIENT, 'type'=>'label', 'align'=>'left', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>$access_by_usertype, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),
			'appointment_date'   => array('title'=>_DATE, 'type'=>'label', 'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'date', 'format_parameter'=>$date_format),
			'appointment_time'   => array('title'=>_TIME, 'type'=>'time', 'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'time', 'format_parameter'=>''),
			'status'             => array('title'=>_STATUS, 'type'=>'enum',  'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'source'=>$arr_statuses_view),
			//'visit_duration'     => array('title'=>_VISIT_DURATION, 'type'=>'label', 'align'=>'center', 'width'=>'120px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>'', 'post_html'=>' '._MIN.' '),
		);
		if($objLogin->GetLoggedType() == 'patient'){
			$this->arrViewModeFields['doctor_name'] = array('title'=>_DOCTOR, 'type'=>'link',  'align'=>'left', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>true, 'tooltip'=>_CLICK_TO_VIEW, 'maxlength'=>'', 'href'=>'index.php?page=doctor_info&docid={doctor_id}', 'target'=>'');
		}


		//---------------------------------------------------------------------- 
		// ADD MODE
		// - Validation Type: alpha|numeric|float|alpha_numeric|text|email|ip_address|password|date
		// 	 Validation Sub-Type: positive (for numeric and float)
		//   Ex.: 'validation_type'=>'numeric', 'validation_type'=>'numeric|positive'
		// - Validation Max Length: 12, 255... Ex.: 'validation_maxlength'=>'255'
		// - Validation Min Length: 4, 6... Ex.: 'validation_minlength'=>'4'
		// - Validation Max Value: 12, 255... Ex.: 'validation_maximum'=>'99.99'
		//---------------------------------------------------------------------- 
		// define add mode fields
		$this->arrAddModeFields = array(
										
		);

		//---------------------------------------------------------------------- 
		// EDIT MODE
		// - Validation Type: alpha|numeric|float|alpha_numeric|text|email|ip_address|password|date
		//   Validation Sub-Type: positive (for numeric and float)
		//   Ex.: 'validation_type'=>'numeric', 'validation_type'=>'numeric|positive'
		// - Validation Max Length: 12, 255... Ex.: 'validation_maxlength'=>'255'
		// - Validation Min Length: 4, 6... Ex.: 'validation_minlength'=>'4'
		// - Validation Max Value: 12, 255... Ex.: 'validation_maximum'=>'99.99'
		// - for editable passwords they must be defined directly in SQL : '.$this->tableName.'.user_password,
		//---------------------------------------------------------------------- 
		$this->EDIT_MODE_SQL = 'SELECT
								'.$this->tableName.'.'.$this->primaryKey.',
								'.$this->tableName.'.appointment_number,
								'.$this->tableName.'.appointment_description,
								'.$this->tableName.'.doctor_id,
								'.$this->tableName.'.doctor_speciality_id,
								'.$this->tableName.'.patient_id,
								'.$this->tableName.'.appointment_date,
								'.$this->tableName.'.appointment_time,
								DATE_FORMAT('.$this->tableName.'.appointment_time, "'.$sql_time_format.'") as mod_appointment_time,
								'.$this->tableName.'.visit_duration,
								'.$this->tableName.'.visit_price,
								'.$this->tableName.'.additional_info,
								'.$this->tableName.'.for_whom,
								'.$this->tableName.'.status,
								'.$this->tableName.'.status_changed,
								'.$this->tableName.'.email_sent,
								CONCAT(d.first_name, " ", d.middle_name, " ", d.last_name) as doctor_name,
								CONCAT(d.work_phone, IF(d.work_phone != "", ", ", ""), d.work_mobile_phone) as doctor_phones,
								CONCAT(p.first_name, " ", p.last_name) as patient_name,
								s.name as specialty_name
							FROM '.$this->tableName.'
								INNER JOIN '.TABLE_DOCTORS.' as d ON '.$this->tableName.'.doctor_id = d.id
								LEFT OUTER JOIN '.TABLE_PATIENTS.' as p ON '.$this->tableName.'.patient_id = p.id
								LEFT OUTER JOIN '.TABLE_SPECIALITIES.' as s ON '.$this->tableName.'.doctor_speciality_id = s.id
							WHERE '.$this->tableName.'.'.$this->primaryKey.' = _RID_';		
		// define edit mode fields
		$this->arrEditModeFields = array(		
			'appointment_number'  => array('title'=>_APPOINTMENT_NUMBER, 'type'=>'label'),
			'appointment_description' => array('title'=>_DESCRIPTION, 'type'=>'label'),
			'doctor_name'    	=> array('title'=>_DOCTOR, 'type'=>'label'),
			'specialty_name' 	=> array('title'=>_SPECIALITY, 'type'=>'label'),
			'doctor_phones'  	=> array('title'=>_DOCTOR_PHONES, 'type'=>'label'),
			'patient_name'   	=> array('title'=>_PATIENT, 'type'=>'label'),
			'appointment_date'  => array('title'=>_DATE, 'type'=>'label', 'format'=>'date', 'format_parameter'=>$date_format),
			'mod_appointment_time' => array('title'=>_TIME, 'type'=>'label', 'format'=>'time'),
			'visit_duration' 	=> array('title'=>_VISIT_DURATION, 'type'=>'label', 'post_html'=>' '._MIN),
			'visit_price' 		=> array('title'=>_PRICE, 'type'=>'label', 'pre_html'=>$currency_symbol),
			'for_whom' 			=> array('title'=>_FOR_WHOM, 'type'=>'enum', 'source'=>$arr_for_whom, 'readonly'=>true),
			'additional_info'  	=> array('title'=>_ADDITIONAL_INFO, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'90px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_maxlength'=>'1024', 'validation_type'=>'', 'unique'=>false),
			'status'      		=> array('title'=>_STATUS, 'type'=>'enum', 'width'=>'', 'required'=>true, 'readonly'=>!$change_appt_in_past, 'default'=>'', 'source'=>$arr_statuses_edit, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
		);

		//---------------------------------------------------------------------- 
		// DETAILS MODE
		//----------------------------------------------------------------------
		$this->DETAILS_MODE_SQL = $this->EDIT_MODE_SQL;
		$this->arrDetailsModeFields = array(
			'appointment_number'  => array('title'=>_APPOINTMENT_NUMBER, 'type'=>'label'),
			'appointment_description'  => array('title'=>_DESCRIPTION, 'type'=>'label'),
			'doctor_name'    => array('title'=>_DOCTOR, 'type'=>'label'),
			'specialty_name' => array('title'=>_SPECIALITY, 'type'=>'label'),
			'doctor_phones'  => array('title'=>_DOCTOR_PHONES, 'type'=>'label'),
			'patient_name'   => array('title'=>_PATIENT, 'type'=>'label'),
			'appointment_date'     => array('title'=>_DATE, 'type'=>'label', 'format'=>'date', 'format_parameter'=>$date_format),
			'mod_appointment_time' => array('title'=>_TIME, 'type'=>'label', 'format'=>'time'),
			'visit_duration' => array('title'=>_VISIT_DURATION, 'type'=>'label', 'post_html'=>' '._MIN),
			'visit_price' => array('title'=>_PRICE, 'type'=>'label', 'pre_html'=>$currency_symbol),
			'for_whom' => array('title'=>_FOR_WHOM, 'type'=>'enum', 'source'=>$arr_for_whom),
			'additional_info'  => array('title'=>_ADDITIONAL_INFO, 'type'=>'label'),
			'status'      => array('title'=>_STATUS, 'type'=>'enum', 'source'=>$arr_statuses_edit),
		);

		///////////////////////////////////////////////////////////////////////////////
		// #004. add translation fields to all modes
		/// $this->AddTranslateToModes(
		/// $this->arrTranslations,
		/// array('name'        => array('title'=>_NAME, 'type'=>'textbox', 'width'=>'410px', 'required'=>true, 'maxlength'=>'', 'readonly'=>false),
		/// 	  'description' => array('title'=>_DESCRIPTION, 'type'=>'textarea', 'width'=>'410px', 'height'=>'90px', 'required'=>false, 'readonly'=>false)
		/// )
		/// );
		///////////////////////////////////////////////////////////////////////////////			

	}
	
	//==========================================================================
    // Class Destructor
	//==========================================================================
    function __destruct()
	{
		// echo 'this object has been destroyed';
    }

	//==========================================================================
    // MicroGrid Methods
	//==========================================================================	
	/**
	 * Before Update
	 */
	public function BeforeUpdateRecord()
	{
	   	//$this->curRecordId - current record

		$sql = "SELECT status FROM ".TABLE_APPOINTMENTS." WHERE id = ".(int)$this->curRecordId;
		$result = database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY);
		if($result[1] > 0){
			$this->status = (int)$result[0]['status'];
		}
		
	   	return true;
	}
	 	
	/**
	 * After Update
	 */
	public function AfterUpdateRecord()
	{
		// $this->curRecordId - currently updated record
	    // $this->params - current record update info
		global $objSettings;
		
		if($this->status == '0' && $this->params['status'] == '1'){

			$admin_email = $objSettings->GetParameter('admin_email');
			$date_format = get_date_format();
			$time_format = get_time_format(false);

			// get appointment's info
			$result = self::GetInfoByID($this->curRecordId);
			$appt_number = isset($result['appointment_number']) ? $result['appointment_number'] : '';
			$docid = isset($result['doctor_id']) ? $result['doctor_id'] : '0';
			$dspecid = isset($result['doctor_speciality_id']) ? $result['doctor_speciality_id'] : '0';
			$patient_id = isset($result['patient_id']) ? $result['patient_id'] : '0';
			$visit_duration = isset($result['visit_duration']) ? $result['visit_duration'] : '0';
			$visit_price = isset($result['visit_price']) ? $result['visit_price'] : '0';
			$for_whom = isset($result['for_whom']) ? $result['for_whom'] : '0';
			$date = isset($result['appointment_date']) ? $result['appointment_date'] : '0';
			$start_time = isset($result['appointment_time']) ? $result['appointment_time'] : '0';
			$date_formatted = date($date_format, strtotime($date));
			$week_day = get_weekday_local(date('w', strtotime($date))+1);
			$start_time_formatted = date($time_format, strtotime($start_time.':00'));
			
			// get patient's info
			$patient_info = Patients::GetPatientInfo($patient_id);
			$patient_fname = isset($patient_info['first_name']) ? $patient_info['first_name'] : '';
			$patient_lname = isset($patient_info['last_name']) ? $patient_info['last_name'] : '';
			$patient_email = isset($patient_info['email']) ? $patient_info['email'] : '';
			$preferred_language = isset($patient_info['preferred_language']) ? $patient_info['preferred_language'] : '';

			// get doctor's info
			$doctor_info = Doctors::GetDoctorInfoById($docid);
			$first_name = isset($doctor_info[0]['first_name']) ? $doctor_info[0]['first_name'] : '';
			$middle_name = isset($doctor_info[0]['middle_name']) ? $doctor_info[0]['middle_name'] : '';
			$last_name = isset($doctor_info[0]['last_name']) ? $doctor_info[0]['last_name'] : '';
			$title = isset($doctor_info[0]['title']) ? $doctor_info[0]['title'] : '';
			$medical_degree = isset($doctor_info[0]['medical_degree']) ? ' - '.$doctor_info[0]['medical_degree'] : '';
			$doc_speciality = Doctors::GetDoctorSpeciality($docid, $dspecid);
			$doc_speciality_name = ($doc_speciality[1] > 0) ? $doc_speciality[0]['speciality_name'] : '';

			$appt_details  = '<table width="100%" border="0" cellspacing="0" cellpadding="3" style="border:1px solid #d1d2d3">';
			$appt_details .= '<tr style="background-color:#e1e2e3;font-weight:bold;font-size:13px;"><th align="left" colspan="2">&nbsp;<b>'._APPOINTMENT_DETAILS.'</b></th></tr>';
			$appt_details .= '<tr><td width="25%">'._APPOINTMENT_NUMBER.': </td><td>'.$appt_number.'</td></tr>';
			$appt_details .= '<tr><td>'._DESCRIPTION.': </td><td>'._APPOINTMENT_WITH_DOCTOR.'</td></tr>';
			$appt_details .= '<tr><td>'._WHEN.': </td><td>'.$date_formatted.' '._AT_TIME.' '.$start_time_formatted.' ('.$week_day.')</td></tr>';
			$appt_details .= '<tr><td>'._WITH.': </td><td>'.$title.' '.$first_name.' '.$middle_name.' '.$last_name.' '.$medical_degree.'</td></tr>';
			$appt_details .= '<tr><td>'._DOCTOR_SPECIALITY.': </td><td>'.$doc_speciality_name.'</td></tr>';
			$appt_details .= '<tr><td>'._DURATION_OF_VISIT.': </td><td>'.$visit_duration.' '._MINUTES.'</td></tr>';
			$appt_details .= '<tr><td>'._WHO_IS_APPOINTMENT_FOR.' </td><td>'.(($for_whom == '0') ? _FOR_ME.' ('.$patient_fname.' '.$patient_lname.')' : _SOMEONE_ELSE).'</td></tr>';
			$appt_details .= '<tr><td>'._PRICE.': </td><td>'.Currencies::PriceFormat($visit_price).'</td></tr>';
			$appt_details .= '</table><br />';
			
			////////////////////////////////////////////////////////////
			send_email(
				$patient_email,
				$admin_email,
				'appointment_approved_by_admin',
				array(
					'{FIRST NAME}' => $patient_fname,
					'{LAST NAME}'  => $patient_lname,
					'{APPOINTMENT NUMBER}'  => $appt_number,
					'{APPOINTMENT DETAILS}' => $appt_details
				),
				$preferred_language
			);
			////////////////////////////////////////////////////////////
		}
	}

	/**
	 * Before Delete
	 */
	public function BeforeDeleteRecord()
	{
	    // $this->curRecordId - current record
		$appointment_info = $this->GetInfoByID($this->curRecordId);
		$date = isset($appointment_info['appointment_date']) ? $appointment_info['appointment_date'] : '0000-00-00';
		$time = isset($appointment_info['appointment_time']) ? $appointment_info['appointment_time'] : '00:00:00';
		
		if($date.' '.$time <= @date('Y-m-d H:i:s')){
			$this->error = _APPOINTMENT_DELETE_IN_PAST_ALERT;
			return false;	
		}
		return true;	
	}


	//==========================================================================
    // Static Methods	
	//==========================================================================	
	/**
	 * Returns static message
	 */
	public static function GetStaticMessage()
	{
		return self::$static_message;
	}

	/**
	 * Verify Appointment 
	 * 		@param $params
	 */
	public static function VerifyAppointment($params = true)
	{
		$docid = isset($params['docid']) ? $params['docid'] : '';		
		$schid = isset($params['schid']) ? $params['schid'] : '';
		$date = isset($params['date']) ? $params['date'] : '0000-00-00';
		$start_time = isset($params['start_time']) ? str_replace('-', ':', $params['start_time']) : '00:00:00';
		$duration = isset($params['duration']) ? $params['duration'] : '';
		$dspecid = isset($params['dspecid']) ? $params['dspecid'] : '';
		$for_whom = isset($params['for_whom']) ? $params['for_whom'] : '';		
		$week_day = (date('w', strtotime($date.' '.$start_time)) + 1);
		
		// check if a doctor is available for this time
		$sql = 'SELECT
					sch.id,
					sch.date_from,
					sch.date_to,
					schtb.time_from,
					schtb.time_to,
					schtb.week_day
				FROM '.TABLE_SCHEDULES.' sch
					INNER JOIN '.TABLE_SCHEDULE_TIMEBLOCKS.' schtb ON sch.id = schtb.schedule_id
					'.(($dspecid != '') ? 'INNER JOIN '.TABLE_DOCTORS_SPECIALITIES.' dspec ON sch.doctor_id = dspec.doctor_id ' : '').'					
				WHERE
					'.(($dspecid != '') ? 'dspec.speciality_id = '.(int)$dspecid.' AND ' : '').'					
					sch.doctor_id  = '.(int)$docid.' AND
					sch.id  = '.(int)$schid.' AND
					(sch.date_from <= \''.$date.'\' AND \''.$date.'\' <= sch.date_to) AND
					schtb.week_day = '.$week_day.' AND
					(schtb.time_from <= \''.$start_time.'\' AND \''.$start_time.'\' < schtb.time_to) AND
					schtb.time_slots = '.(int)$duration.'';	
		
		if(database_query($sql, ROWS_ONLY) > 0){
			return true;			
		}
		return false;	
	}

	/**
	 * Draw Appointment Details
	 * 		@param $param
	 * 		@param $draw
	 */
	public static function DrawVerifyAppointment($params = array(), $draw = true)
	{
		global $objLogin;

		$date_format = get_date_format();
		$time_format = get_time_format(false);
		
		$docid = isset($params['docid']) ? $params['docid'] : '';		
		$schid = isset($params['schid']) ? $params['schid'] : '';
		$date = isset($params['date']) ? $params['date'] : '';
		$date_formatted = isset($params['date']) ? date($date_format, strtotime($params['date'])) : '';
		$week_day = get_weekday_local(date('w', strtotime($params['date']))+1);
		$start_time = isset($params['start_time']) ? $params['start_time'] : '';
		$start_time_formatted = isset($params['start_time']) ? date($time_format, strtotime(str_replace('-', ':', $params['start_time']).':00')) : '';
		$duration = isset($params['duration']) ? $params['duration'] : '';
		$dspecid = isset($params['dspecid']) ? $params['dspecid'] : '';
		$for_whom = isset($params['for_whom']) ? $params['for_whom'] : '';

		$output = '';
		
		$doctor_info = Doctors::GetDoctorInfoById($docid);
		
		$output .= '<form action="index.php?patient=appointment_completed" method="post">';
		$output .= '<table width="100%" id="tblAppointmentDetails">';
		$output .= draw_token_field(false);
		$output .= draw_hidden_field('task', 'complete_appointment', false);
		$output .= draw_hidden_field('docid', $docid, false);
		$output .= draw_hidden_field('schid', $schid, false);
		$output .= draw_hidden_field('date', $date, false);
		$output .= draw_hidden_field('start_time', $start_time, false);
		$output .= draw_hidden_field('duration', $duration, false);
		$output .= draw_hidden_field('dspecid', $dspecid, false);
		$output .= draw_hidden_field('for_whom', $for_whom, false);
		$output .= '<tr>';
			if($doctor_info[1]){
				
				$first_name = isset($doctor_info[0]['first_name']) ? $doctor_info[0]['first_name'] : '';
				$middle_name = isset($doctor_info[0]['middle_name']) ? $doctor_info[0]['middle_name'] : '';
				$last_name = isset($doctor_info[0]['last_name']) ? $doctor_info[0]['last_name'] : '';
				$title = isset($doctor_info[0]['title']) ? $doctor_info[0]['title'] : '';
				$medical_degree = isset($doctor_info[0]['medical_degree']) ? ' - '.$doctor_info[0]['medical_degree'] : '';
				$doctor_photo_thumb = (isset($doctor_info[0]['doctor_photo_thumb']) && ($doctor_info[0]['doctor_photo_thumb'] != '')) ? $doctor_info[0]['doctor_photo_thumb'] : 'doctor_'.$doctor_info[0]['gender'].'.png';
		
				$output .= '<td width="370px">
						<div class="doctor_card">								
							<div style="width:100px;float:left;"><img width="90px" src="images/doctors/'.$doctor_photo_thumb.'" alt="" /></div>
							<div style="width:230px;float:left;">
								'._WHEN.': <b>'.$date_formatted.'</b> '._AT_TIME.' <b>'.$start_time_formatted.'</b> ('.$week_day.') <br />										
								'._WITH.': <b>'.$title.' '.$first_name.' '.$middle_name.' '.$last_name.' '.$medical_degree.'</b><br>
								'._DURATION_OF_VISIT.': <b>'.$duration.' '._MIN.'</b> 
							</div>								
						<div>
					</td>
					<td>';
								
				$output .= _DOCTOR_SPECIALITY.'<br>';
				$doc_speciality = Doctors::GetDoctorSpeciality($docid, $dspecid);
				if($doc_speciality[1] > 0){					
					$output .= '<b>'.$doc_speciality[0]['speciality_name'].'</b><br><br>';
				}						

				$output .= _WHO_IS_APPOINTMENT_FOR.'<br>';
				$output .= '<b>'.(($for_whom == '0') ? _FOR_ME : _SOMEONE_ELSE).'</b>';
				
				$output .= '<br><br>
							</td>';									
				$output .= '</tr>';
				$output .= '<tr><td colspan="2" nowrap="nowrap" height="10px"></td></tr>';
				$output .= '<tr>';
				$output .= '<td></td><td><input type="submit" value="'._MAKE_APPOINTMENT.'"></td>';
				$output .= '</tr>';
			}
		$output .= '</tr>';
		$output .= '</table>';
		$output .= '</form>';
		
		if($draw) echo $output;
		else return $output;
	}

	/**
	 * Draw Appointment Details
	 * 		@param $params
	 * 		@param $draw
	 */
	public static function DrawAppointmentDetails($params = array(), $draw = true)
	{
		global $objLogin;		

		$date_format = get_date_format();
		$time_format = get_time_format(false);

		$docid = isset($params['docid']) ? $params['docid'] : '';
		$dspecid = isset($params['dspecid']) ? $params['dspecid'] : '';
		$schid = isset($params['schid']) ? $params['schid'] : '';
		$date = isset($params['date']) ? $params['date'] : '';
		$date_formatted = isset($params['date']) ? date($date_format, strtotime($params['date'])) : '';
		$week_day = get_weekday_local(date('w', strtotime($params['date']))+1);
		$start_time = isset($params['start_time']) ? $params['start_time'] : '';
		$start_time_formatted = isset($params['start_time']) ? date($time_format, strtotime(str_replace('-', ':', $params['start_time']).':00')) : '';
		$duration = isset($params['duration']) ? $params['duration'] : '';
		
		$output = '';
		
		$doctor_info = Doctors::GetDoctorInfoById($docid);
		$action = $objLogin->IsLoggedInAsPatient() ? 'patient=appointment_verify' : 'page=checkout_signin';
		
		$output .= '<form action="index.php?'.$action.'" method="post">';
		$output .= '<table width="100%" id="tblAppointmentDetails">';
		$output .= draw_token_field(false);
		$output .= draw_hidden_field('task', 'verify_appointment', false);
		$output .= draw_hidden_field('docid', $docid, false);
		$output .= draw_hidden_field('schid', $schid, false);
		$output .= draw_hidden_field('date', $date, false);
		$output .= draw_hidden_field('start_time', $start_time, false);
		$output .= draw_hidden_field('duration', $duration, false);
		$output .= '<tr>';
			if($doctor_info[1]){
				
				$first_name = isset($doctor_info[0]['first_name']) ? $doctor_info[0]['first_name'] : '';
				$middle_name = isset($doctor_info[0]['middle_name']) ? $doctor_info[0]['middle_name'] : '';
				$last_name = isset($doctor_info[0]['last_name']) ? $doctor_info[0]['last_name'] : '';
				$title = isset($doctor_info[0]['title']) ? $doctor_info[0]['title'] : '';
				$medical_degree = isset($doctor_info[0]['medical_degree']) ? ' - '.$doctor_info[0]['medical_degree'] : '';
				$doctor_photo_thumb = (isset($doctor_info[0]['doctor_photo_thumb']) && ($doctor_info[0]['doctor_photo_thumb'] != '')) ? $doctor_info[0]['doctor_photo_thumb'] : 'doctor_'.$doctor_info[0]['gender'].'.png';
		
				$output .= '<td width="370px">
						<div class="doctor_card">								
							<div class="photo"><img width="90px" src="images/doctors/'.$doctor_photo_thumb.'" alt="" /></div>
							<div class="description">
								'._WHEN.': <b>'.$date_formatted.'</b> '._AT_TIME.' <b>'.$start_time_formatted.'</b> ('.$week_day.') <br />										
								'._WITH.': <b>'.$title.' '.$first_name.' '.$middle_name.' '.$last_name.' '.$medical_degree.'</b><br>
								'._DURATION_OF_VISIT.': <b>'.$duration.' '._MIN.'</b> 
							</div>								
						<div>
					</td>
					<td>';
								
				$output .= _DOCTORS_SPECIALITIES.'<br>';
				$doc_specialities = Doctors::GetDoctorSpecialities($docid);
				if($doc_specialities[1] > 0){
					$output .= '<select name="dspecid">';
					for($i=0; $i<$doc_specialities[1]; $i++){
						$output .= '<option '.(($doc_specialities[0][$i]['speciality_id'] == $dspecid) ? 'selected="selected"' : '').' value="'.$doc_specialities[0][$i]['speciality_id'].'">'.$doc_specialities[0][$i]['speciality_name'].'</option>';
					}
					$output .= '</select><br><br>';
				}						

				$output .= _WHO_IS_APPOINTMENT_FOR.'<br>';
				$output .= '<select name="for_whom">';
				$output .= '<option value="0">'._FOR_ME.'</option>';
				$output .= '<option value="1">'._SOMEONE_ELSE.'</option>';							
				$output .= '</select><br><br>';
	
				$output .= '</td>';									
				$output .= '</tr>';
				$output .= '<tr><td colspan="2" nowrap="nowrap" height="10px"></td></tr>';
				$output .= '<tr>';
				$output .= '<td></td><td><input type="submit" value="'._BOOK_NOW.'"></td>';
				$output .= '</tr>';
			}
		$output .= '</tr>';
		$output .= '</table>';
		$output .= '</form>';

		if($draw) echo $output;
		else return $output;
	}
	
	/**
	 * Draw Appointment SignIn
	 * 		@param $draw
	 */
	public static function DrawAppointmentSignIn($draw = true)
	{
		$appointment_details = &$_SESSION['appointment_details'];
		$appointment_details['docid']	   = isset($_POST['docid']) ? prepare_input($_POST['docid']) : '';
		$appointment_details['dspecid']    = isset($_POST['dspecid']) ? prepare_input($_POST['dspecid']) : '';
		$appointment_details['for_whom']   = isset($_POST['for_whom']) ? prepare_input($_POST['for_whom']) : '';
		$appointment_details['schid'] 	   = isset($_POST['schid']) ? prepare_input($_POST['schid']) : '';
		$appointment_details['date'] 	   = isset($_POST['date']) ? prepare_input($_POST['date']) : '';
		$appointment_details['start_time'] = isset($_POST['start_time']) ? prepare_input($_POST['start_time']) : '';
		$appointment_details['duration']   = isset($_POST['duration']) ? prepare_input($_POST['duration']) : '';	
			
		Patients::DrawLoginFormBlock();
	}
	
	/**
	 * Place appointment into databse
	 * 		@param $params
	 */
	public static function DoAppointment($params = array())
	{
        global $objLogin, $objSettings;
		
        if(SITE_MODE == 'demo'){
           self::$static_error = _OPERATION_BLOCKED;
		   return false;
        }
		
		$docid = isset($params['docid']) ? $params['docid'] : '';		
		$schid = isset($params['schid']) ? $params['schid'] : '';
		$date = isset($params['date']) ? $params['date'] : '0000-00-00';
		$start_time = isset($params['start_time']) ? str_replace('-', ':', $params['start_time']) : '00:00:00';
		$duration = isset($params['duration']) ? $params['duration'] : '';
		$dspecid = isset($params['dspecid']) ? $params['dspecid'] : '';
		$for_whom = isset($params['for_whom']) ? $params['for_whom'] : '';
		$date_format = get_date_format();
		$time_format = get_time_format(false);

		$sql = 'SELECT id, appointment_number
				FROM '.TABLE_APPOINTMENTS.'
				WHERE
					doctor_id = '.(int)$docid.' AND 
					patient_id = '.(int)$objLogin->GetLoggedID().' AND
					appointment_date = \''.$date.'\' AND
					appointment_time = \''.$start_time.':00\'';
		$result = database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY);
		if($result[1] > 0){
			self::$static_error = _APPOINTMENT_ALREADY_BOOKED_ALERT;
			return false;
		}else{
			
			// check if patient has reached the maximum number of allowed 'open' appointments
			$max_appointments = ModulesSettings::Get('appointments', 'maximum_allowed_appointments');
			$approval_required = ModulesSettings::Get('appointments', 'approval_required');
			$send_appt_copy_to_admin =  ModulesSettings::Get('appointments', 'send_appointment_copy_to_admin');
			
			$sql = 'SELECT COUNT(*) as cnt
					FROM '.TABLE_APPOINTMENTS.'
					WHERE patient_id = '.(int)$objLogin->GetLoggedID().' AND status = 0';				
			$result = database_query($sql, DATA_ONLY);
			$cnt = isset($result[0]['cnt']) ? (int)$result[0]['cnt'] : 0;
			if($cnt >= $max_appointments){
				self::$static_error = _MAX_APPOINTMENTS_ERROR;
				return false;
			}		
			
			// get doctor's info
			$doctor_info = Doctors::GetDoctorInfoById($docid);
			$visit_price = isset($doctor_info[0]['default_visit_price']) ? $doctor_info[0]['default_visit_price'] : '0';
			$first_name = isset($doctor_info[0]['first_name']) ? $doctor_info[0]['first_name'] : '';
			$middle_name = isset($doctor_info[0]['middle_name']) ? $doctor_info[0]['middle_name'] : '';
			$last_name = isset($doctor_info[0]['last_name']) ? $doctor_info[0]['last_name'] : '';
			$title = isset($doctor_info[0]['title']) ? $doctor_info[0]['title'] : '';
			$medical_degree = isset($doctor_info[0]['medical_degree']) ? ' - '.$doctor_info[0]['medical_degree'] : '';
			$doc_speciality = Doctors::GetDoctorSpeciality($docid, $dspecid);
			$doc_speciality_name = ($doc_speciality[1] > 0) ? $doc_speciality[0]['speciality_name'] : '';
			$date_formatted = date($date_format, strtotime($date));
			$week_day = get_weekday_local(date('w', strtotime($date))+1);
			$start_time_formatted = date($time_format, strtotime($start_time.':00'));
			
			if($approval_required == 'by email'){
				$msg = _APPT_CREATED_CONF_BY_EMAIL_MSG;
				$email_template = 'new_appointment_confirm_by_email';					
				$status = '0';
			}else if($approval_required == 'by admin'){
				$msg = _APPT_CREATED_CONF_BY_ADMIN_MSG;
				$email_template = 'new_appointment_confirm_by_admin';					
				$status = '0';
			}else{
				// automatic				
				$msg = _APPOINTMENT_SUCCESS_BOOKED;
				$email_template = 'new_appointment_accepted';
				$status = '1';
			}

			$appt_number = strtoupper(get_random_string(10));
			$sql = 'INSERT INTO '.TABLE_APPOINTMENTS.'(
					id,
					appointment_number,
					appointment_description,
					doctor_id,
					doctor_speciality_id,
					patient_id,
					appointment_date,
					appointment_time,
					visit_duration,
					visit_price,
					additional_info,
					for_whom,
					status,
					status_changed,
					email_sent
				)VALUES(
					NULL,
					\''.$appt_number.'\',
					\'Appointment with a doctor\',
					'.(int)$docid.',
					'.(int)$dspecid.',
					'.(int)$objLogin->GetLoggedID().',
					\''.$date.'\',
					\''.$start_time.':00\',
					'.(int)$duration.',
					'.(int)$visit_price.',
					\'\',
					\''.$for_whom.'\',
					'.(int)$status.',
					\'0000-00-00 00:00:00\',
					0
				)
			';
			if(database_void_query($sql)){
				self::$static_message = $msg;
				
				////////////////////////////////////////////////////////////
				$sender = $objSettings->GetParameter('admin_email');
				$admin_copy_subject = 'Patient has booked appointment (admin copy)';
				$patient_fname = $objLogin->GetLoggedFirstName();
				$patient_lname = $objLogin->GetLoggedLastName();
				
				$appt_details  = '<table width="100%" border="0" cellspacing="0" cellpadding="3" style="border:1px solid #d1d2d3">';
				$appt_details .= '<tr style="background-color:#e1e2e3;font-weight:bold;font-size:13px;"><th align="left" colspan="2">&nbsp;<b>'._APPOINTMENT_DETAILS.'</b></th></tr>';
				$appt_details .= '<tr><td width="25%">'._APPOINTMENT_NUMBER.': </td><td>'.$appt_number.'</td></tr>';
				$appt_details .= '<tr><td>'._DESCRIPTION.': </td><td>'._APPOINTMENT_WITH_DOCTOR.'</td></tr>';
				$appt_details .= '<tr><td>'._WHEN.': </td><td>'.$date_formatted.' '._AT_TIME.' '.$start_time_formatted.' ('.$week_day.')</td></tr>';
				$appt_details .= '<tr><td>'._WITH.': </td><td>'.$title.' '.$first_name.' '.$middle_name.' '.$last_name.' '.$medical_degree.'</td></tr>';
				$appt_details .= '<tr><td>'._DOCTOR_SPECIALITY.': </td><td>'.$doc_speciality_name.'</td></tr>';
				$appt_details .= '<tr><td>'._DURATION_OF_VISIT.': </td><td>'.$duration.' '._MINUTES.'</td></tr>';
				$appt_details .= '<tr><td>'._WHO_IS_APPOINTMENT_FOR.' </td><td>'.(($for_whom == '0') ? _FOR_ME.' ('.$patient_fname.' '.$patient_lname.')' : _SOMEONE_ELSE).'</td></tr>';
				$appt_details .= '<tr><td>'._PRICE.': </td><td>'.Currencies::PriceFormat($visit_price).'</td></tr>';
				$appt_details .= '</table><br />';									
				
				send_email(
					$objLogin->GetLoggedEmail(),
					$sender,
					$email_template,
					array(
						'{FIRST NAME}' => $patient_fname,
						'{LAST NAME}'  => $patient_lname,
						'{BASE URL}'   => APPHP_BASE,
						'{APPOINTMENT NUMBER}'  => $appt_number,
						'{APPOINTMENT DETAILS}' => $appt_details
					),
					$objLogin->GetPreferredLang(),
					(($send_appt_copy_to_admin == 'yes') ? $sender : ''),
					(($send_appt_copy_to_admin == 'yes') ? $admin_copy_subject : '')
				);
				////////////////////////////////////////////////////////////
				return true;	
			}else{
				//echo mysql_error();
				self::$static_error = _BOOKING_APPOINTMENT_ERROR;
				return false;
			}
		}		
	}
	
}
?>